/*
 * Serial.c
 *
 * Created: 4/10/2011 10:23:22
 *  Author: morpheus
 */
#include "XmegaSerial.h"


int uart_putc(char c)
{
 
    // Wait for the transmit buffer to be empty
    while ( !( USARTC0.STATUS & USART_DREIF_bm) );
 
    // Put our character into the transmit buffer
    USARTC0.DATA = c; 
 
    return 0;
}
void uart_puts(const char *message)
{
	while(*message)
	  uart_putc(*message++);
}	
 
// Init USART.  Transmit only (we're not receiving anything)
// We use USARTC0, transmit pin on PC3.
// Want 9600 baud. Have a 2 MHz clock. BSCALE = 0
// BSEL = ( F_CPU / (2^0 * 16*9600)) -1 = 12
// Fbaud = 2000000 / (2^0 * 16 * (12+1))  = 9615 bits/sec
void uart_init (uint32_t baud)
{
  uint32_t div1k;
  uint8_t bscale = 0;
  uint16_t bsel;

  div1k = ((F_CPU*128) / baud) - 1024;
  while ((div1k < 2096640) && (bscale < 7)) {
    bscale++;
    div1k <<= 1;
  }

  bsel = div1k >> 10;

  USARTC0.BAUDCTRLA = bsel&0xff;
  USARTC0.BAUDCTRLB = (bsel>>8) | ((16-bscale) << 4);

  // Set the TxD pin high - set PORTC DIR register bit 3 to 1
  PORTC.OUTSET = PIN3_bm;
 
  // Set the TxD pin as an output - set PORTC OUT register bit 3 to 1
  PORTC.DIRSET = PIN3_bm;
 
  // Set baud rate & frame format
  //USARTC0.BAUDCTRLB = 0;			// BSCALE = 0 as well
  //USARTC0.BAUDCTRLA = 207; // 32MHz
  //USARTC0.BAUDCTRLA = 12; // 2MHz
 
  // Set mode of operation
  USARTC0.CTRLA = 0;				// no interrupts please
  USARTC0.CTRLC = 0x03;			// async, no parity, 8 bit data, 1 stop bit
 
  // Enable transmitter only
  USARTC0.CTRLB = USART_TXEN_bm;
}

uint8_t xmega_usart_setspeed (USART_t *usart, uint32_t baud) 
{
  return 1;
}
